02. Async Promises

JS Async Keywords

Async Promises

While there have always been some async work arounds in JS, including setTimeout(), and AJAX, more recently a tool called Promises has been introduced natively to JavaScript, and Promises are now the accepted best practice for writing asynchronous functions in JavaScript.

You can think of Promises as a special function that either satisfy (resolve) or fail (reject) to execute a task, and then executes the corresponding actions, usually another task with the returned data in the case of 'resolved' and usually throw an error in the case of 'reject'.

Here is the basic anatomy of a Promise:

var promise = new Promise(function(resolve, reject) {
  // do a thing, possibly async, then…

  if (/* everything turned out fine */) {
    resolve("Stuff worked!");
  }
  else {
    reject(Error("It broke"));
  }
});

Code Demo

There are many methods to handle asynchronous work already, however Promises are the recommended option because they give you flexibility, intuitive syntax, and easy error handling. Promises are an amazing development in JavaScript, but until ES2017 (ES8) they still required extra boilerplate code, called generators, to run asynchronously. Now however, with the addition of native async functions to JavaScript, we can easily apply the async keywords to a Promise to execute asynchronous JavaScript code.

To make a fetch() call, or any other methods inside of a function, asynchronous we must use the keywords provided by JavaScript. Here is an example of what it would look like to turn the fetch function from the previous example into an asynchronous function:

Code Demo

const postData = async ( url = '', data = {})=>{
    // console.log(data)
      const response = await fetch(url, {
      method: 'POST', // *GET, POST, PUT, DELETE, etc.
      credentials: 'same-origin', // include, *same-origin, omit
      headers: {
          'Content-Type': 'application/json',
      },
      body: JSON.stringify(data), // body data type must match "Content-Type" header        
    });

      try {
        const newData = await response.json();
        console.log(newData);
        return newData
      }catch(error) {
      console.log("error", error);
      // appropriately handle the error
      }
  }

  postData('/addMovie', {movie:' the matrix', score: 5})

Async JS Example Prep

postData is an async arrow function that is called with parameters on the last line of code. It is asynchronous because of the keyword async placed before its parameters. Once you mark a function as 'async' you have access to the keywords await, try, and catch which mirror the underlying Promise functionality of resolving or rejecting a condition-- here the condition is successfully making a POST request to the specified route. The await keyword is used in places where the next actions requires data from the current action so we want to tell our program to wait until the data has been received before continuing with the next steps-- this is the magic of ASYNC JavaScript.

Async JS Quiz

Which of these amazing ‘facts’ are also true about asynchronous JavaScript

SOLUTION:
  • Native Promises in JavaScript allow for asynchronous functions that are dependent on satisfying a condition.
  • JavaScript functions can be made asynchronous simply by using the keyword `async`.
  • JavaScript functions denoted by the keyword `async` allow for the syntax of `await`, `try`, `catch`, for an elegant way of dealing with code asynchronously.

Async JS Summary

In the next lesson we will learn how to pair JavaScript async fetch functions with Web APIS to unleash the dynamic power of front-end programming.

Async JS Further Research

More on Async JS

For a more detailed overview on Promises and why they matter, read the article here.